import axios from 'axios';
import {message} from 'antd';

const API_BASE_URL = 'http://localhost:8080/api';

const api = axios.create({
    baseURL: API_BASE_URL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
    },
});

// 文件上传专用API实例
const uploadApi = axios.create({
    baseURL: API_BASE_URL,
    timeout: 30000, // 30秒超时，适合大文件上传
    headers: {
        'Content-Type': 'multipart/form-data',
    },
});

// 请求拦截器
api.interceptors.request.use(
    (config) => {
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
api.interceptors.response.use(
    (response) => {
        // 后端返回 ApiResponse 格式: {code: 200, data: actualData, message: "..."}
        // 如果响应包含标准的ApiResponse字段，直接返回data部分
        const responseData = response.data;
        if (responseData && typeof responseData === 'object' && 'code' in responseData && 'data' in responseData) {
            // 如果是成功响应，返回data字段；否则抛出错误
            if (responseData.code === 200) {
                return responseData.data;
            } else {
                return Promise.reject(new Error(responseData.message || '请求失败'));
            }
        }
        // 如果不是标准格式，直接返回数据
        return responseData;
    },
    (error) => {
        if (error.response) {
            const errorData = error.response.data;
            if (errorData && typeof errorData === 'object') {
                if (errorData.message) {
                    message.error(errorData.message);
                } else if (errorData.detail) {
                    message.error(errorData.detail);
                } else {
                    message.error('请求失败');
                }
            } else {
                message.error('请求失败');
            }
        } else if (error.request) {
            message.error('网络连接失败');
        } else {
            message.error('请求配置错误');
        }
        return Promise.reject(error);
    }
);

// 文件上传API的响应拦截器
uploadApi.interceptors.response.use(
    (response) => {
        // 提取data字段以适配ApiResponse格式
        const responseData = response.data;
        if (responseData && typeof responseData === 'object' && 'code' in responseData && 'data' in responseData) {
            if (responseData.code === 200) {
                return responseData.data;
            } else {
                return Promise.reject(new Error(responseData.message || '请求失败'));
            }
        }
        return responseData;
    },
    (error) => {
        const errorData = error.response?.data;
        const errorMessage = errorData?.message || error.message || '请求失败';
        message.error(errorMessage);
        return Promise.reject(new Error(errorMessage));
    }
);

// 路线API - 注意：移除了getAll方法，必须通过dataId获取指定批次数据
export const routesAPI = {
    getById: (id) => api.get(`/routes/${id}`),
    getByDataId: (dataId) => api.get('/routes/by-data', {params: {dataId}}),
    getByType: (routeType) => api.get(`/routes/type/${routeType}`),
};

// 货物API - 注意：移除了getAll方法，必须通过dataId获取指定批次数据
export const shipmentsAPI = {
    getById: (id) => api.get(`/shipments/${id}`),
    getByDataId: (dataId) => api.get('/shipments/by-data', {params: {dataId}}),
    search: (params) => api.get('/shipments/search', {params}),
};

// 匹配结果API
export const matchingAPI = {
    getResultsByDataId: (dataId) => api.get(`/match-results/results/${dataId}`),
    getAllByDataId: (dataId) => api.get(`/match-results/all/${dataId}`),
    getDetailsByDataId: (dataId) => api.get(`/match-results/details/${dataId}`),
    getByRouteId: (routeId) => api.get(`/match-results/route/${routeId}`),
    getById: (id) => api.get(`/match-results/${id}`),
};

// 任务API
export const taskAPI = {
    getAll: () => api.get('/tasks'),
    getByDataId: (dataId) => api.get('/tasks/by-data', {params: {dataId}}),
    getById: (id) => api.get(`/tasks/${id}`),
};

// 数据上传API - 新版批次流程
export const uploadDataAPI = {
    /**
     * 创建新的批次
     * @param {string} description - 批次描述信息（可选）
     * @param {number} governmentSubsidy - 政府补贴（百分比）（可选）
     * @param {number} timeValue - 时间价值（百分比）（可选）
     * @returns {Promise} 批次信息，包含batchId
     */
    createBatch: async (description, governmentSubsidy, timeValue) => {
        try {
            const response = await api.post('/upload/batch', null, {
                params: {
                    description,
                    governmentSubsidy,
                    timeValue,
                },
            });
            return response;
        } catch (error) {
            console.error('创建批次失败:', error);
            throw error;
        }
    },

    /**
     * 更新批次元数据
     * @param {number} dataId - 数据ID
     * @param {string} description - 批次描述信息
     * @param {number} governmentSubsidy - 政府补贴（百分比）
     * @param {number} timeValue - 时间价值（百分比）
     * @returns {Promise} 操作结果
     */
    updateBatchMetadata: async (dataId, description, governmentSubsidy, timeValue) => {
        try {
            const response = await api.put('/upload/batch/metadata', null, {
                params: {
                    dataId,
                    description,
                    governmentSubsidy,
                    timeValue,
                },
            });
            return response;
        } catch (error) {
            console.error('更新批次元数据失败:', error);
            throw error;
        }
    },

    /**
     * 获取批次元数据
     * @param {number} dataId - 数据ID
     * @returns {Promise} 批次元数据
     */
    getBatchMetadata: async (dataId) => {
        try {
            const response = await api.get('/upload/batch/metadata', {
                params: {dataId},
            });
            return response;
        } catch (error) {
            console.error('获取批次元数据失败:', error);
            throw error;
        }
    },

    /**
     * 上传路线CSV文件
     * @param {File} file - 路线CSV文件
     * @param {number} batchId - 批次ID
     * @returns {Promise} 上传结果
     */
    uploadRouteCsv: async (file, batchId) => {
        try {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('batchId', batchId);

            const response = await uploadApi.post('/upload/routes', formData, {
                onUploadProgress: (progressEvent) => {
                    const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                    console.log(`上传进度: ${percentCompleted}%`);
                },
            });
            return response;
        } catch (error) {
            console.error('上传路线文件失败:', error);
            throw error;
        }
    },

    /**
     * 上传货物CSV文件
     * @param {File} file - 货物CSV文件
     * @param {number} batchId - 批次ID
     * @returns {Promise} 上传结果
     */
    uploadShipmentCsv: async (file, batchId) => {
        try {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('batchId', batchId);

            const response = await uploadApi.post('/upload/shipments', formData, {
                onUploadProgress: (progressEvent) => {
                    const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                    console.log(`上传进度: ${percentCompleted}%`);
                },
            });
            return response;
        } catch (error) {
            console.error('上传货物文件失败:', error);
            throw error;
        }
    },

    /**
     * 获取批次统计信息
     * @param {number} dataId - 批次ID
     * @returns {Promise} 批次统计信息
     */
    getBatchStats: async (dataId) => {
        try {
            const response = await api.get(`/upload/batch/${dataId}/stats`);
            return response;
        } catch (error) {
            console.error('获取批次统计信息失败:', error);
            throw error;
        }
    },

    /**
     * 获取批次列表（分页）
     * @param {number} page - 页码（从1开始）
     * @param {number} size - 每页大小
     * @returns {Promise} 批次列表
     */
    getBatchList: async (page = 1, size = 10) => {
        try {
            const response = await api.get('/upload/batch/list', {
                params: {page, size},
            });
            return response;
        } catch (error) {
            console.error('获取批次列表失败:', error);
            throw error;
        }
    },
};

// 算法执行API
export const algorithmAPI = {
    /**
     * 执行匹配算法（同步）
     * @param {number} dataId - 数据ID
     * @returns {Promise} 执行结果
     */
    execute: async (dataId) => {
        try {
            const response = await api.post('/algorithm/execute', null, {
                params: {dataId},
                timeout: 300000, // 5分钟超时
            });
            return response;
        } catch (error) {
            console.error('算法执行失败:', error);
            throw error;
        }
    },

    /**
     * 执行匹配算法（异步）
     * @param {number} dataId - 数据ID
     * @returns {Promise} 任务启动结果
     */
    executeAsync: async (dataId) => {
        try {
            const response = await api.post('/algorithm/execute/async', null, {
                params: {dataId},
            });
            return response;
        } catch (error) {
            console.error('异步算法执行启动失败:', error);
            throw error;
        }
    },

    /**
     * 获取SSE事件源以订阅任务状态
     * @param {string} taskId - 任务ID
     * @returns {EventSource} SSE事件源
     */
    subscribeToTaskStatus: (taskId) => {
        const eventSource = new EventSource(`${API_BASE_URL}/algorithm/sse/status/${taskId}`);
        return eventSource;
    },
};

export default api;